<template>
	<base-page-view class-name="page-container">
    <view class="main">
      <view class="top-box">
        <view class="about" @click="about">关于碧选</view>
      </view>
      <view class="phone-send">
        <view class="title">赠送99元VIP会员卡</view>
        <view class="time-box">
          倒计时<text class="num">{{count_down.hour}}</text>时<text class="num">{{count_down.minute}}</text>分<text class="num">{{count_down.second}}</text>秒
        </view>
        <view class="input-box">
          <view class="ipnone-box" @click="goPhine">
            <text>{{countryCode}}</text>
            <b-image width="10" height="6" src="/static/images/mine/sanjiao.png" is-asset class="sanjiao"/>
          </view>
          <input class="input" v-if="countryCode==='+86'" v-model="mobile" type="number" maxlength="11" placeholder-class="input-holder" :placeholder="'请输入您的手机号'" />
          <input class="input" v-else v-model="mobile" type="number" maxlength="20" placeholder-class="input-holder" :placeholder="'请输入您的手机号'" />
        </view>
        <view class="input-box">
          <view class="ipnone-box">
          </view>
          <input class="input" placeholder="请输入验证码"  type="number" v-model="checkCode" maxlength="6"/>
          <view class="getNum" v-if="count_num==60" @click="getCode()">{{first_code_get?'获取验证码':'重新获取'}}</view>
          <view class="getNum" v-else>{{count_num}}s后重新获取</view>
        </view>
        <view class="get-btn" @click="tackCard()">立即领取</view>
      </view>
      <view class="qy-box">
        <view class="title">VIP会员专享权益</view>
        <view class="zx-content">
          <view class="zx-box" v-for="(item,index) in qy_list" :key="index" @click="go_url(item)">
            <b-image :src="item.icon_url" mode="widthFix" width="80" height="80"/>
            <view class="name">{{item.title}}</view>
          </view>
        </view>
      </view>
      <view class="tip-box">最终解释权归碧选所有</view>
      <!-- 分类推荐 -->
      <view class="home-container" v-if="cateRecommendList.length">
        <view class="sticky-wrapper" :class="{hasSubTitle: hasSubTitle}" :style="'top: 0px'">
          <horizontal-list list-name="cate-recommend" :list="cateRecommendList" :other-params="{hasSubTitle}" @itemClick="cateRecommendClick">
            <template v-slot="{item, otherParams}">
              <view class="title" :class="{noSubTitle: !item.subtitle}">{{ item.title }}</view>
              <view v-if="otherParams.hasSubTitle" class="sub-title" :class="{disabled: !item.subtitle}">{{ item.subtitle || '-' }}</view>
            </template>
          </horizontal-list>
        </view>
        <waterFall ref="waterFall" :list="cateRecommendGoodsList" :min-height="minHeight">
          <template v-slot="{ item, columnIndex, index }">
            <view class="goods-item" :class="{mini: columnIndex === 1 && index===0}" @click="goodsClick(item)">
              <view class="bg">
                <b-image class-name="item-image" :src="item.pic" mode="aspectFill" />
                <view class="content">
                  <view class="item-name">{{ item.title }}</view>
                  <view v-if="item.diamond_price" class="item-commission">钻石价 ￥{{ item.diamond_price }}</view>
                  <view class="item-footer">
                    <view class="price">{{ item.price }}</view>
                    <view v-if="item.volume" class="sale">已售{{ item.volume }}件</view>
                  </view>
                </view>
              </view>
            </view>
          </template>
          <template slot="footer">
            <base-list-state :list-length="listLength" :list-query="goodsQuery" :list-state="goodsState" :list-empty="listEmpty" @btnClick="emptyBtnClick" />
          </template>
        </waterFall>
      </view>
      <!-- 领取成功弹窗 -->
      <view class="seccess-box" v-if="show_success">
        <view class="back-box">
          <view class="ts-box">
            <view class="btn1" @click.stop.prevent="$navigateTo('/pagesMember/member/index')">我的会员中心</view>
            <view class="btn2" @click.stop.prevent="goHome()">首页</view>
            <b-image class="close" src="/images/mine/close.png" is-asset mode="widthFix" width="38" height="38" @click="show_success=false"/>
          </view>
        </view>
      </view>
    </view>
	</base-page-view>
</template>

<script>
  import { h5NavigateTo, toFunctionDetail, toGoods,toMpHomePage } from '@/utils/navigateTo'
  import { arraySplit, debounce } from '@/utils/tools'
  import searchBar from '@/components/searchBar/index'
  import baseSwiper from '@/components/base/base-swiper.vue'
  import horizontalList from '@/components/horizontalList/index'
  import waterFall from '@/components/waterFall/index'
  import baseListState from '@/components/base/base-list-state'
  import share from '@/components/draw/share'
  import './give.scss'
	export default {
    components: {
      searchBar,
      baseSwiper,
      horizontalList,
      waterFall,
      baseListState,
      share
    },
		data() {
			return {
				// 分类推荐模块
        cateRecommendList: [],
        hasSubTitle: false,
        goodsQuery: {
          id: '',
          pageIndex: 1,
          pageSize: 10
        },
        goodsState: {
          loading: false,
          more: true
        },
        cateRecommendGoodsList: [],
        goodsListLength: 0,
        needRefreshGoodsList: false,
        listEmpty: {
          type: 'empty_commodity',
          text: '暂无商品',
          btnText: '刷新'
        },
        minHeight: 0,
        //会员
        card_id:"",
        countryCode: '+86',
        card_detail:{},//卡详情
        qy_list:[],//权益列表
        remaining_time:0,//剩余时间
        timer:"",//剩余时间定时器
        count_time:"",
        count_num:60,//验证码倒计时
        mobile:"",//手机号
        checkCode:"",//验证码
        show_success:false,
        first_code_get:true,//第一次获取验证码
			}
		},
    computed: {
      listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
        return this.cateRecommendGoodsList.length
      },
      //倒计时
      count_down(){
        // 总秒数
        var second = Math.floor(this.remaining_time / 1000);
        // 小时
        var hr = Math.floor(second / 3600);
        // 分钟
        var min = Math.floor(second / 60 % 60);
        // 秒
        var sec = Math.floor(second % 60);
        let time={
          "hour":hr,
          "minute":min,
          "second":sec
        }
        return time;
      },
      memberType() {
        switch (this.userInfo.current_member_card_type){
          case 0:
            return "普通会员"
            break;
          case 1:
            return "VIP会员"
            break;
          case 2:
            return "钻石会员"
            break;
          case 3:
            return "董事会员"
            break;
          default:
            return ""
            break;
        }
      }
    },
    destroyed() {
      // clearInterval(this.timer);
      // clearInterval(this.count_time);
    },
    onLoad(option) {
      if (uni.getStorageSync('countryCode')) {
        this.countryCode = uni.getStorageSync('countryCode')
      }
      if(option.id){
        this.card_id=option.id;
      }else{
        uni.showToast({title: '未获取到分享id',icon: 'none'})
        return
      }
      this.getClassify();
      this.getCard();
    },
    onShow() {
      if (uni.getStorageSync('countryCode')) {
        this.countryCode = uni.getStorageSync('countryCode')
      }
    },
    onReachBottom(){
      if (this.goodsQuery.id && this.goodsState.more && !this.goodsState.loading) {
        this.goodsQuery.pageIndex++
        this.getRecommendGoods()
      }
    },
		methods: {
      about(){
        this.$navigateTo('/pagesMaterial/article/index?id=3&title=走进碧选');
      },
      goHome(){
        toMpHomePage();
      },
      //会员权益跳转
      go_url(item){
        toFunctionDetail(item);
      },
      //领取会员卡
      async tackCard(){
        if(!this.card_id){
          uni.showToast({title: '未获取到分享id',icon: 'none'})
          return;
        }
        // status状态：1-有效，2-已过期，3-已领取"
        if(this.card_detail.status==2){
          this.$msg('会员卡已过期');
          return;
        }
        if(this.card_detail.status==3){
          this.$msg('会员卡已被领取');
          return;
        }
        if(!this.remaining_time||this.remaining_time<1000){
          this.$gc.$message({
            content: "会员卡已失效，请联系好友重新赠送",
            type: 'richText',
            title: "提示",
            showMessage: true,
            showCancel: false,
            confirmText: '确认',
            align: 'center'
          })
          return;
        }
        // if(this.token){
        //   if(this.userInfo.current_member_card_type>0){
        //     this.$gc.$message({
        //       content: `您已是${this.memberType}，不可领取`,
        //       type: 'richText',
        //       title: "提示",
        //       showMessage: true,
        //       showCancel: false,
        //       confirmText: '确认',
        //       align: 'center'
        //     })
        //     return;
        //   }
        // }
        if(!this.mobile){
          uni.showToast({title: '请输入手机号',icon: 'none'})
          return;
        }
        if (!(/^\d{11}$/.test(this.mobile.replace(/\s*/g, ''))) && this.countryCode === '+86') {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
            duration: 2 * 1000
          })
          return;
        }
        if(!this.checkCode){
          uni.showToast({
            title: '请输入验证码',
            icon: 'none',
            duration: 2 * 1000
          })
          return;
        }
        const res = await this.$api.mineApi.receiveCard({
          cardId: this.card_id,
          checkCode:this.checkCode,
          mobile:this.mobile,
          regionCode:this.countryCode
        });
        if(res.code==0){
          this.show_success=true;
        }
      },
      //获取验证码
      async getCode(){
        // status状态：1-有效，2-已过期，3-已领取"
        if(this.card_detail.status==2){
          this.$msg('会员卡已过期');
          return;
        }
        if(this.card_detail.status==3){
          this.$msg('会员卡已被领取');
          return;
        }
        if(!this.mobile){
          uni.showToast({
            title: '请输入手机号',
            icon: 'none',
          })
          return;
        }
        if (!(/^\d{11}$/.test(this.mobile.replace(/\s*/g, ''))) && this.countryCode === '+86') {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
            duration: 2 * 1000
          })
          return;
        }
        const res = await this.$api.mineApi.sendCode({
          mobile: this.mobile,
          region_code:this.countryCode
        });
        if(res.code==0){
          uni.showToast({
            title: '发送成功',
            icon: 'none',
          })
          this.set_count_time();
          this.first_code_get=false;
          return;
        }
      },
      //验证码倒计时
      set_count_time(){
        this.count_num--;
        this.count_time=setInterval(_=>{
          if(this.count_num<=1){
            clearInterval(this.count_time);
            this.count_num=60;
          }else{
            this.count_num--;
          }
        },1000)
        this.$on('hook:deactivated', () => {
          clearInterval(this.count_time);                                    
        })
      },
      //选择区号
      goPhine(){
        this.$navigateTo('/customComponent/phoneList')
      },
      //获取会员卡详情
      async getCard(){
        if(!this.card_id){return}
        const res = await this.$api.mineApi.getCardDetail({
          id: this.card_id
        });
        if(res.code==0){
          this.card_detail=res.data.user_member_card_v_o;
          let d = new Date();
          this.remaining_time=res.data.user_member_card_v_o.end_time-d.getTime();
          this.qy_list=res.data.user_privilege_config_v_os;
          if(this.remaining_time&&this.remaining_time>0){
            if(this.remaining_time>86400000){
              this.remaining_time=86400000;
            }
            this.timer=setInterval(_=>{
              this.remaining_time-=1000;
            },1000);
            this.$once('hook:beforeDestroy', () => {            
              clearInterval(this.timer);                                    
            })
          }else{
            this.remaining_time=0;
          }
        }
      },
			async getClassify(isRefresh){
        const res = await this.$api.homeApi.getHomeDetail({
          hideLoading: !!isRefresh
        })
        if (res.success && res.data) {
          this.initHomeData(res.data, isRefresh)
        }
        uni.stopPullDownRefresh()
      },
      initHomeData(homeData, isRefresh) {
        const {  cateRecommendList } = homeData;
        this.cateRecommendList = cateRecommendList || []
        this.hasSubTitle = this.cateRecommendList.some(i => i.subtitle)
        if (!isRefresh && this.cateRecommendList.length) {
          this.goodsQuery.id = this.cateRecommendList[0].id;
          this.getRecommendGoods();
        }
      },
      // 获取首页推荐分类商品
      async getRecommendGoods(query) {
        const goodsQuery = query || this.goodsQuery
        if (!goodsQuery.id) {
          return
        }
        this.goodsState.loading = true
        this.minHeight = this.systemInfo.screenHeight - 167
        const res = await this.$api.homeApi.getHomeRecommendGoods({ ...goodsQuery })
        if (goodsQuery.pageIndex === 1) {
          this.cateRecommendGoodsList = []
          this.goodsListLength = 0
        }
        if (res.success) {
          this.listEmpty.text = '暂无商品'
          const goodsList = (res.data || [])
          goodsList.map(item => {
            item.price = (item.price || 0).toFixed(2)
            item.diamond_price = (item.diamond_price || 0).toFixed(2)
            let volume = ''
            const nVolume = Number(item.volume)
            if (nVolume > 0) {
              volume = nVolume
              if (nVolume > 9999) {
                volume = (Math.floor((nVolume / 1000)) / 10).toFixed(1) + '万'
              }
              if (nVolume > 99999999) {
                volume = (Math.floor((nVolume / 10000000)) / 10).toFixed(1) + '亿'
              }
            }
            item.volume = volume
            let text = ''
            let commission = 0
            if (this.token && this.userInfo.level > 1) {
              text = '返收益¥'
              commission = item[['', '', 'region_commission', 'director_commission'][this.userInfo.level]]
            } else {
              text = '升级VIP省¥'
              commission = item.region_commission
            }
            if (commission > 0) {
              item.commission_result = `${text}${commission.toFixed(2)}`
            }
          })
          this.goodsState.more = goodsList.length === goodsQuery.pageSize
      
          if (goodsQuery.pageIndex === 1) {
            this.cateRecommendGoodsList = goodsList
            this.goodsListLength = goodsList.length
            this.$nextTick(() => {
              this.$refs.waterFall.init()
            })
          } else if (goodsList.length) {
            this.goodsListLength += goodsList.length
            this.$refs.waterFall.addToList(goodsList)
          }
        } else {
          this.listEmpty.text = res.msg
          this.goodsState.more = false
        }
        this.goodsState.loading = false
      },
      // 点击分类推荐
      cateRecommendClick(index) {
        this.goodsQuery.id = this.cateRecommendList[index].id
        this.goodsQuery.pageIndex = 1
        this.getRecommendGoods()
        this.$trackSDK.track('bx.home.tab.click', this.goodsQuery.id, {
          title: this.cateRecommendList[index].title,
          ad_id: this.goodsQuery.id
        })
      },
      // 点击分类推荐商品
      goodsClick(item) {
        this.$trackSDK.track('bx.home.sale.click', '', {
          title: '商品列表',
          good_id: item.goods_id,
          good_name: item.title
        })
        toGoods(item)
      },
      emptyBtnClick() {
        this.goodsQuery.pageIndex = 1
        this.goodsState.more = true
        console.log(4)
        this.getRecommendGoods()
      },
		}
	}
</script>

<style lang="scss" scoped>
.main{
  background-color: rgb(9,8,8);
}
.top-box{
  background: url('https://asset-uat.bisinuolan.cn/bixuan_uni/images/mine/member-back.png') no-repeat;
  background-size: 100% auto;
  height: 1008rpx;
  position: relative;
  .about{
    position: absolute;
    right: 0rpx;
    top: 38rpx;
    font-size: 28rpx;
    color: rgba(255, 253, 251, 0.8);
    font-family: PingFang SC;
    font-weight: 400;
    border-top-left-radius: 100rpx;
    border-bottom-left-radius: 100rpx;
    background: rgba(255, 196, 165, 0.23); 
    padding: 16rpx 25rpx 17rpx 35rpx;
  }
}
.phone-send{
  width: 666rpx;
  // height: 618rpx;
  padding-bottom: 68rpx;
  background: linear-gradient(0.0009000000000014552deg, #1D1F1F 0%, #322F2C 100%);
  border-radius: 30rpx 30rpx 30rpx 30rpx;
  margin: -42rpx auto 0rpx;
  .title{
    font-size: 42rpx;
    font-family: SimHei;
    font-weight: 400;
    color: #FFEBD2;
    background: linear-gradient(180deg, #FFEEE4 0%, #FFC1A1 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-align: center;
    padding-top: 42rpx;
  }
  .time-box{
    font-size: 30rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #FFE8DB;
    line-height: 43rpx;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 31rpx;
    .num{
      background: #000000;
      padding: 0rpx 6rpx;
      margin: 0rpx 10rpx;
    }
  }
  .input-box{
    background-color: white;
    display: flex;
    align-items: center;
    height: 100rpx;
    border-radius: 1000rpx;
    margin: 32rpx 54rpx 0rpx;
    padding: 0rpx 27rpx;
    .ipnone-box{
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      line-height: 36rpx;
      margin-right: 14rpx;
      // min-width: 64rpx;
      display: flex;
      align-items: center;
      .sanjiao{
        margin-left: 8rpx;
      }
    }
    .input{
      flex: 1;
      line-height: 1.5;
    }
    .getNum{
      background: #302E2B;
      border-radius: 100rpx;
      font-size: 26rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #F8F8F8;
      padding: 14rpx 20rpx;
      min-width: 100rpx;
      text-align: center;
    }
  }
  .get-btn{
    background: linear-gradient(180deg, rgb(253,228,201) 0%, rgb(234,173,121) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100rpx;
    border-radius: 1000rpx;
    margin: 48rpx 54rpx 0rpx;
    color: #663403;
    font-size: 42rpx;
    font-family: SimHei;
    font-weight: 400;
  }
}
.qy-box{
  width: 666rpx;
  padding-bottom: 28rpx;
  background: linear-gradient(0.0009000000000014552deg, #1D1F1F 0%, #322F2C 100%);
  border-radius: 30rpx 30rpx 30rpx 30rpx;
  margin: 33rpx auto 40rpx;
  .title{
    font-size: 42rpx;
    font-family: SimHei;
    font-weight: 400;
    color: #FFEBD2;
    background: linear-gradient(180deg, #FFEEE4 0%, #FFC1A1 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-align: center;
    padding-top: 42rpx;
    margin-bottom: 63rpx;
  }
  .zx-content{
    text-align: center;
    display: flex;
    flex-wrap:wrap;
    .zx-box{
      width: 25%;
      margin-bottom: 36rpx;
      .name{
        font-size: 26rpx;
        margin-top: 10rpx;
        color: #F4BF8F;
      }
    }
  }
}
.tip-box{
  font-size: 24rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #FFFFFF;
  line-height: 34rpx;
  opacity: 0.38;
  text-align: center;
  margin-bottom: 75rpx;
}
.seccess-box{
  .back-box{
    position: fixed;
    top: 0rpx;
    left: 0rpx;
    right: 0rpx;
    bottom: 0rpx;
    z-index: 1000;
    background-color: rgba(0,0,0,0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    .ts-box{
      background: url('https://asset-uat.bisinuolan.cn/bixuan_uni/static/images/member/pay/get-success.png') no-repeat;
      background-size: 100% auto;
      width: 748rpx;
      height: 604rpx;
      text-align: center;
      position: relative;
      .btn1{
        margin: 404rpx auto 27rpx;
        width: 370rpx;
        height: 85rpx;
        background: linear-gradient(90deg, #DBB191 0%, #F7DFC3 100%);
        box-shadow: 0px 10px 30px 0px rgba(0, 0, 0, 0.5);
        color: #78482F;
        font-size: 30rpx;
        border-radius: 1000rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .btn2{
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #F4DBC0;
      }
      .close{
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom:-80rpx;
      }
    }
  }
}
</style>
